<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading">
      <text>加载中...</text>
    </view>

    <!-- 文章详情 -->
    <view v-else>
      <text class="title">{{ article.title }}</text>
      <view class="meta">
        <text>发布于：{{ formatDate(article.publish_time) }}</text>
        <text>作者ID：{{ article.psy_id }}</text> <!-- 显示作者ID -->
      </view>
      <view class="content">
        <rich-text :nodes="article.content"></rich-text> <!-- 假设文章内容是HTML格式 -->
      </view>
    </view>

    <!-- 错误提示 -->
    <view v-if="error" class="error">
      <text>{{ error }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      article: {
        psy_id: null,
        title: '',
        publish_time: '',
        author_id: null, // 作者ID
        content: '' // 假设文章内容是富文本或HTML字符串
      },
      isLoading: true, // 加载状态
      error: '' // 错误信息
    };
  },
  onLoad(options) {
    // 从页面跳转参数中获取文章ID
    const articleId = options.id;
    if (articleId) {
      this.fetchArticleDetail(articleId);
    } else {
      this.error = '文章ID缺失';
      this.isLoading = false;
    }
  },
  methods: {
    // 根据文章ID获取文章详情
    async fetchArticleDetail(articleId) {
      this.isLoading = true;
      this.error = '';
      try {
        const res = await uni.request({
          url: `http://127.0.0.1:5001/api_1_0/article/${articleId}`, // 后端 API 地址
          method: 'GET'
        });

        if (res.statusCode === 200) {
          this.article = res.data.data[0]; // 假设返回的数据结构是 { code: 200, data: [{...}] }
        } else {
          this.error = '获取文章详情失败';
          uni.showToast({ title: '获取文章详情失败', icon: 'none' });
        }
      } catch (err) {
        console.error('获取文章详情时出错:', err);
        this.error = '加载失败，请稍后再试';
        uni.showToast({ title: '加载失败，请稍后再试', icon: 'none' });
      } finally {
        this.isLoading = false;
      }
    },
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    }
  }
};
</script>

<style>
.container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  line-height: 1.4;
}

.meta {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.content {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  line-height: 1.6;
  font-size: 16px;
  color: #333;
}

.loading,
.error {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  font-size: 16px;
  color: #666;
}

.error {
  color: #ff4d4f;
}
</style>